package eyou.net.treeview;

import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;
import org.w3c.dom.Node;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import eyou.net.tree.TreeListViewAdapter;
import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class MainActivity extends AppCompatActivity{

    private int mId;
    boolean  firstRoot=true;
    private String userParam = "?q=data&type=user&pid=";
    private String groupParam = "?q=data&type=group&pid=";
    private List<Object> mDatas2 = new ArrayList<Object>();
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private ListView mTree;
    private GroupTreeAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_dept_layout);
        mTree = (ListView) findViewById(R.id.id_tree);
        try
        {
            mAdapter = new GroupTreeAdapter(mTree, this, mDatas2, 10);

            mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                @Override
                public void onClick(eyou.net.tree.Node node, int position) {
                    if (node.isLeaf())
                    {
                        Toast.makeText(getApplicationContext(), node.getName(),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

        mTree.setAdapter(mAdapter);

        Authenticate("", groupParam, 0,0);

    }


    public void matchGroup(okhttp3.Response response, int pid,String param,int  clickCount ) {
        JSONObject resultObjectGroup = null;
        try {
            resultObjectGroup = NetUtil.getInstance().fetch35EIS(response);
            Gson gson = new Gson();
            if (param.contains("type=group")) {
                ContactGroupBean contactGroupBean = gson.fromJson(String.valueOf(resultObjectGroup), ContactGroupBean.class);
                grouplist.clear();
                grouplist.addAll(contactGroupBean.getGroup());
                for (int i = 0; i < grouplist.size(); i++) {
                    int _id = Integer.parseInt(grouplist.get(i).getGroup_id());

                    Dept dept = new Dept(_id, pid, grouplist.get(i).getGroup_name());

                    if (clickCount>0){
                        dept.set_parent(mLinkedList.get(clickCount));
                    }

                    nodes.add(dept);
                }
            }else{
                ContactBean.UserBean contactGroupBean = gson.fromJson(String.valueOf(resultObjectGroup), ContactBean.UserBean.class);
                userlist.clear();
                userlist.add(contactGroupBean);
                for (int i = 0; i < userlist.size(); i++) {
                    if(null!=userlist.get(i).getAcct_id()) {
                        int _id = Integer.parseInt(userlist.get(i).getAcct_id());

                        Dept dept = new Dept(_id, pid, userlist.get(i).getReal_name());

                        if (clickCount>0){
                            dept.set_parent(mLinkedList.get(clickCount));
                        }

                        nodes.add(dept);
                    }
                }
            }

//
//            ContactGroupBean contactGroupBean = gson.fromJson(String.valueOf(resultObjectGroup), ContactGroupBean.class);
//            grouplist.clear();
//            grouplist.addAll(contactGroupBean.getGroup());
//
//
//            List<Node> nodes = new ArrayList<>();

//            for (int i = 0; i < grouplist.size(); i++) {
//                int _id = Integer.parseInt(grouplist.get(i).getGroup_id());
//                nodes.add(new Dept(_id, pid, grouplist.get(i).getGroup_name()));
//            }
            if (mLinkedList != null) {
                if (mLinkedList.size() == 0&&firstRoot) {
                    mLinkedList.addAll(nodes);
                    nodes.clear();
                    firstRoot=false;
                } else {
                    if (pid == (Integer) mLinkedList.get(clickCount).get_parentId()) {
                        mLinkedList.get(clickCount).get_childrenList().clear();
                        mLinkedList.get(clickCount).get_childrenList().addAll(nodes);
                    }
                    List<Node> items = mLinkedList.get(clickCount).get_childrenList();
                    items.clear();
                    items.addAll(nodes);
                    nodes.clear();
//                        if (items != null && items.size() > 0) {
//                            for (int j = 0; j < items.size(); j++) {
//                                if (pid == (Integer) items.get(j).get_id()) {
//                                    items.get(j).get_childrenList().clear();
//                                    items.get(j).get_childrenList().addAll(nodes);
//                                }
//                            }
//                        }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);

    }


    /**
     * zhouyy  Get  请求   basic认证
     * 网络请求
     *
     * @return
     */
    public void Authenticate(final String account, final String param, final int groupId, final int clickID) {
        OkHttpClient client = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        System.out.println("Authenticating for response: " + response);
                        System.out.println("Challenges: " + response.challenges());
                        String credential = Credentials.basic("admin@test.eyou.net", "eyouadmin");
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
                .build();
        Request request = new Request.Builder()
                .url(NetUtil.FETCH_EIS_URL + param + groupId)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG--->onFailure", "result1");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("TAG--->onResponse", "result");
                if (response.isSuccessful()) {
                        matchGroup(response, groupId,param,clickID);
                    }


            }
        });
    }
}
